package com.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.manage.common.lang.Result;
import com.manage.entity.Book;
import com.manage.entity.Warehousing;
import com.manage.mapper.BookMapper;
import com.manage.mapper.WarehousingMapper;
import com.manage.service.IBookService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 教材管理业务实现类
 */
@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements IBookService {
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private WarehousingMapper warehousingMapper;

    /**
     * 入库教材
     * @param book
     */
    @Transactional
    @Override
    public void saveBook(Book book) {
        //先更具书名查询是否包含教材
        Long inventory = book.getInventory();//数量
        Book bookDB = bookMapper.selectOne(new QueryWrapper<Book>().eq("book_name", book.getBookName()));
        if(bookDB!=null){
            //如果包含教材，则修改库存
            bookDB.setInventory(bookDB.getInventory()+inventory);
            bookMapper.updateById(bookDB);
            //添加入库记录
            Warehousing warehousing = new Warehousing();
            warehousing.setBookId(Integer.valueOf(bookDB.getId()));
            warehousing.setCount(inventory);
            warehousing.setCreateTime(LocalDateTime.now());
            warehousingMapper.insert(warehousing);
        }else{
            //如果不包含教材，则添加教材
            LocalDateTime date=LocalDateTime.now();
            book.setCreateTime(date);
            bookMapper.insert(book);
            //添加入库记录
            Warehousing warehousing = new Warehousing();
            warehousing.setBookId(Integer.valueOf(book.getId()));
            warehousing.setCount(inventory);
            warehousing.setCreateTime(LocalDateTime.now());
            warehousingMapper.insert(warehousing);
        }

    }
}
